import random
import string

from alibabacloud_dysmsapi20170525.client import Client
from alibabacloud_tea_openapi.models import Config
from alibabacloud_dysmsapi20170525.models import SendSmsRequest
from alibabacloud_tea_util.models import RuntimeOptions
import json


class Send_SMS():
    access_key_id = 'LTAI5tLu8tNo8XjtfNPJWTD7'
    access_key_secret = 'eOhmfpEExNHtD5IsX1dA0vaeT7p3Li'
    endpoint = 'dysmsapi.aliyuncs.com'
    sign_name = '阿里云短信测试'
    template_code = 'SMS_154950909'

    def __init__(self):
        self.config = Config(
            # 必填，您的 AccessKey ID,
            access_key_id=self.access_key_id,
            # 必填，您的 AccessKey Secret,
            access_key_secret=self.access_key_secret,
            endpoint=self.endpoint
        )

    def send(self, mobile: str, code: str):
        """
        mobile: 手机号
        code：验证码
        """
        # 1. 创建一个客服端
        client = Client(self.config)
        send_sms_request = SendSmsRequest(
            phone_numbers=mobile,
            template_param=json.dumps({"code": code}),
            sign_name=self.sign_name,
            template_code=self.template_code,

        )
        # 2. 创建短信对象
        # 3. 设置允许时间选项
        runtime = RuntimeOptions()
        #
        try:
            # 4. 发送短信
            res = client.send_sms_with_options(send_sms_request, runtime)
            if res.body.code == 'OK':
                return {'code': "OK", "message": "短信发送成功！"}
            else:
                return {'code': "NO", "error": res.body.message}
        except Exception as e:
            return {'code': "NO", "message": "短信发送失败！"}

    def get_random_code(self):
        """ 随机生成6位数的验证码 """
        code = ''.join([random.choice(string.digits) for _ in range(6)])
        return code
